package jzbank.dao.serializabledao.impl;

import jzbank.common.exception.SyncException;
import jzbank.dao.serializabledao.FTPInstanceDao;
import jzbank.pojo.comfig.FTPInstancePO;
import jzbank.util.SerializationUtil;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class FTPInstanceDaoImpl implements FTPInstanceDao {

    private static final String DATA_FILE = "./ftpconfig/ftp_instance_data.ser"; // FTP数据文件的文件名

    // 添加FTP信息
    @Override
    public void addFTPInstancePo(FTPInstancePO ftpInstancePo) {
        List<FTPInstancePO> ftpInstancePoList = getAllFTPInstances();
        ftpInstancePoList.add(ftpInstancePo);
        SerializationUtil.serializeObjectToFile(ftpInstancePoList, DATA_FILE);
    }

    // 删除FTP信息
    @Override
    public void deleteFTPInstancePo(String id) {
        List<FTPInstancePO> ftpInstancePoList = getAllFTPInstances();
        ftpInstancePoList.removeIf(ftpInstancePo -> ftpInstancePo.getFid().equals(id));
        SerializationUtil.serializeObjectToFile(ftpInstancePoList, DATA_FILE);

    }

    // 更新FTP信息
    @Override
    public void updateFTPInstancePo(FTPInstancePO updatedFTPInstancePo) {
        List<FTPInstancePO> ftpInstancePoList = getAllFTPInstances();
        for (int i = 0; i < ftpInstancePoList.size(); i++) {
            if (ftpInstancePoList.get(i).getFid().equals(updatedFTPInstancePo.getFid())) {
                ftpInstancePoList.set(i, updatedFTPInstancePo);
                break;
            }
        }

        SerializationUtil.serializeObjectToFile(ftpInstancePoList, DATA_FILE);

    }

    // 获取所有FTP信息
    @Override
    public List<FTPInstancePO> getAllFTPInstances() {
        List<FTPInstancePO> ftpInstancePoList = new ArrayList<>();

        Object obj = SerializationUtil.deserializeObjectFromFile(DATA_FILE);
        if (obj instanceof List<?>) {
            ftpInstancePoList = (List<FTPInstancePO>) obj;
        }

        return ftpInstancePoList;
    }

    // 根据FTP id查找FTP信息
    @Override
    public FTPInstancePO getFTPInstancePoByFid(String fid) {
        List<FTPInstancePO> ftpInstancePoList = getAllFTPInstances();
        FTPInstancePO ftpInstancePo = new FTPInstancePO();
        for (int i = 0; i < ftpInstancePoList.size(); i++) {
            if (ftpInstancePoList.get(i).getFid().equals(fid)) {
                ftpInstancePo = ftpInstancePoList.get(i);
                break;
            }
        }
        return ftpInstancePo;
    }
}
